<!DOCTYPE html>
<html lang="zh-CN">

<head>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天室 - 注册与登录</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- 引入 Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios@1.4.0/dist/axios.min.js"></script>
    <style>
        /* 样式部分保持不变，无需修改 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background: url('./image/bk.jpg');
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            width: 100%;
            max-width: 500px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .card {
            background: rgba(255, 255, 255, 0.5);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            overflow: hidden;
            position: relative;
        }

        .card-header {
            background: #1a73e8;
            color: white;
            padding: 20px;
            text-align: center;
            font-size: 1.5rem;
            font-weight: bold;
        }

        .card-body {
            padding: 30px;
        }

        .form-group {
            margin-bottom: 25px;
            position: relative;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .input-with-icon {
            position: relative;
        }

        .input-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #777;
        }

        input,
        select {
            width: 100%;
            padding: 15px 15px 15px 45px;
            border: 2px solid #ddd;
            border-radius: 10px;
            font-size: 1rem;
            transition: all 0.3s;
        }

        input:focus,
        select:focus {
            border-color: #1a73e8;
            box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
            outline: none;
        }

        .country-select {
            padding-left: 15px;
        }

        .captcha-container {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .captcha-box {
            flex: 1;
            background: #f1f1f1;
            height: 50px;
            border-radius: 8px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1.8rem;
            font-weight: bold;
            letter-spacing: 5px;
            color: #333;
            user-select: none;
            cursor: pointer;
            transition: all 0.3s;
        }

        .captcha-box:hover {
            background: #e0e0e0;
            transform: scale(1.02);
        }

        .btn {
            width: 100%;
            padding: 15px;
            background: #1a73e8;
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn:hover {
            background: #0d62da;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(26, 115, 232, 0.4);
        }

        .btn:disabled {
            background: #cccccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .agreement {
            display: flex;
            align-items: center;
            margin-bottom: 25px;
            font-size: 0.95rem;
            color: #555;
        }

        .agreement input {
            width: auto;
            margin-right: 10px;
        }

        .agreement a {
            color: #1a73e8;
            text-decoration: none;
        }

        .agreement a:hover {
            text-decoration: underline;
        }

        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 30px;
            gap: 30px;
        }

        .step {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .step-circle {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e0e0e0;
            display: flex;
            justify-content: center;
            align-items: center;
            font-weight: bold;
            margin-bottom: 10px;
            color: #888;
            border: 2px solid #ccc;
            transition: all 0.3s;
        }

        .step.active .step-circle {
            background: #1a73e8;
            color: white;
            border-color: #1a73e8;
            transform: scale(1.1);
        }

        .step.completed .step-circle {
            background: #4caf50;
            color: white;
            border-color: #4caf50;
        }

        .step-text {
            font-size: 0.9rem;
            color: #666;
            font-weight: 500;
        }

        .step.active .step-text {
            color: #1a73e8;
            font-weight: bold;
        }

        .success-message {
            text-align: center;
            padding: 30px;
        }

        .success-icon {
            font-size: 5rem;
            color: #4caf50;
            margin-bottom: 20px;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.1);
            }

            100% {
                transform: scale(1);
            }
        }

        .success-message h2 {
            margin-bottom: 15px;
            color: #333;
        }

        .success-message p {
            margin-bottom: 25px;
            color: #555;
            font-size: 1.1rem;
        }

        .login-link {
            text-align: center;
            margin-top: 20px;
            color: #555;
            font-size: 1rem;
        }

        .login-link a {
            color: #1a73e8;
            font-weight: bold;
            text-decoration: none;
            transition: all 0.2s;
        }

        .login-link a:hover {
            text-decoration: underline;
            color: #0d62da;
        }

        .avatar-preview {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: #f1f1f1;
            margin: 0 auto 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            border: 2px solid #ddd;
            cursor: pointer;
            position: relative;
            transition: all 0.3s;
        }

        .avatar-preview:hover {
            border-color: #1a73e8;
            transform: scale(1.05);
        }

        .avatar-preview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            display: none;
        }

        .avatar-preview i {
            font-size: 2.5rem;
            color: #777;
        }

        .hidden {
            display: none;
        }

        .error-message {
            color: #e53935;
            font-size: 0.9rem;
            margin-top: 5px;
            display: none;
        }

        .password-strength {
            height: 5px;
            background: #e0e0e0;
            border-radius: 3px;
            margin-top: 10px;
            overflow: hidden;
        }

        .password-strength-bar {
            height: 100%;
            width: 0;
            background: #e53935;
            transition: width 0.3s;
        }

        .forgot-password {
            text-align: right;
            margin-top: -15px;
            margin-bottom: 20px;
        }

        .forgot-password a {
            color: #1a73e8;
            text-decoration: none;
            font-size: 0.9rem;
        }

        .forgot-password a:hover {
            text-decoration: underline;
        }

        .success-notice {
            background: #e8f5e9;
            border-left: 4px solid #4caf50;
            padding: 10px 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            color: #2e7d32;
            display: none;
        }

        @media (max-width: 600px) {
            .card-body {
                padding: 20px;
            }

            .header h1 {
                font-size: 2rem;
            }

            .step-indicator {
                gap: 15px;
            }
        }
    </style>

</head>

<body>
    <div class="container">
        <div class="header">
            <h1>聊天室</h1>
            <p>连接世界，畅聊无限</p>
        </div>

        <div class="card">
            <!-- 步骤指示器 -->
            <div class="step-indicator" id="step-indicator">
                <div class="step active" id="step1">
                    <div class="step-circle">1</div>
                    <div class="step-text">验证手机号</div>
                </div>
                <div class="step" id="step2">
                    <div class="step-circle">2</div>
                    <div class="step-text">填写账号信息</div>
                </div>
                <div class="step" id="step3">
                    <div class="step-circle">3</div>
                    <div class="step-text">注册成功</div>
                </div>
            </div>

            <!-- 第一步：验证手机号 -->
            <div id="step1-content" class="card-body">
                <div class="form-group">
                    <label for="country">国家/地区</label>
                    <select id="country" class="country-select">
                        <option value="86">中国 (+86)</option>
                        <option value="1">美国 (+1)</option>
                        <option value="44">英国 (+44)</option>
                        <option value="81">日本 (+81)</option>
                        <option value="82">韩国 (+82)</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="phone">手机号</label>
                    <div class="input-with-icon">
                        <i class="fas fa-mobile-alt input-icon"></i>
                        <input type="tel" id="phone" placeholder="建议使用常用手机号">
                    </div>
                    <div class="error-message" id="phone-error"></div>
                </div>

                <div class="form-group">
                    <label for="captcha">验证码</label>
                    <div class="captcha-container">
                        <img id="captcha-image" src="/user/getcode" alt="验证码" style="height: 50px; cursor: pointer;" onclick="refreshCaptcha()">
                        <div class="input-with-icon" style="flex: 2">
                            <i class="fas fa-shield-alt input-icon"></i>
                            <input type="text" id="captcha" placeholder="输入验证码">
                        </div>
                    </div>
                    <div class="error-message" id="captcha-error"></div>
                </div>

                <div class="agreement">
                    <input type="checkbox" id="agreement" checked>
                    <label for="agreement">我已阅读并同意<a href="#">《用户服务协议》</a>和<a href="#">《隐私政策》</a></label>
                </div>

                <button class="btn" id="verify-btn">验证手机号</button>

                <!-- 添加切换链接 -->
                <div class="login-link">
                    已有账号？<a href="#" id="to-login-from-step1">立即登录</a>
                </div>
            </div>

            <!-- 第二步：填写账号信息 -->
            <div id="step2-content" class="card-body hidden">
                <div class="form-group">
                    <label>用户头像</label>
                    <div class="avatar-preview" id="avatar-preview">
                        <i class="fas fa-user"></i>
                        <img id="avatar-img" src="#" alt="头像预览">
                    </div>
                    <input type="file" id="avatar" accept="image/*" class="hidden">
                </div>

                <div class="form-group">
                    <label for="username">用户名</label>
                    <div class="input-with-icon">
                        <i class="fas fa-user input-icon"></i>
                        <input type="text" id="username" placeholder="设置您的用户名">
                    </div>
                    <div class="error-message" id="username-error"></div>
                </div>

                <div class="form-group">
                    <label for="password">设置密码</label>
                    <div class="input-with-icon">
                        <i class="fas fa-lock input-icon"></i>
                        <input type="password" id="password" placeholder="设置登录密码">
                    </div>
                    <div class="password-strength">
                        <div class="password-strength-bar" id="password-strength-bar"></div>
                    </div>
                    <div class="error-message" id="password-error"></div>
                </div>

                <div class="form-group">
                    <label for="confirm-password">确认密码</label>
                    <div class="input-with-icon">
                        <i class="fas fa-lock input-icon"></i>
                        <input type="password" id="confirm-password" placeholder="再次输入密码">
                    </div>
                    <div class="error-message" id="confirm-password-error"></div>
                </div>

                <button class="btn" id="register-btn">完成注册</button>

                <!-- 添加切换链接 -->
                <div class="login-link">
                    已有账号？<a href="#" id="to-login-from-step2">立即登录</a>
                </div>
            </div>

            <!-- 第三步：注册成功 -->
            <div id="step3-content" class="card-body hidden">
                <div class="success-message">
                    <div class="success-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <h2>注册成功！</h2>
                    <p>恭喜您已成功注册聊天室账号</p>
                    <p>请登录后开始使用聊天室</p>
                    <!-- 修改为去登录按钮 -->
                    <button class="btn" id="to-login">去登录</button>
                </div>
            </div>

            <!-- 登录页面 -->
            <div id="login-content" class="card-body hidden">
                <!-- 添加注册成功提示 -->
                <div class="success-notice" id="register-success-notice">
                    <i class="fas fa-check-circle"></i> 注册成功！请使用您的账号登录
                </div>

                <div class="form-group">
                    <label for="login-phone">手机号</label>
                    <div class="input-with-icon">
                        <i class="fas fa-mobile-alt input-icon"></i>
                        <input type="tel" id="login-phone" placeholder="请输入您的手机号">
                    </div>
                    <div class="error-message" id="login-phone-error"></div>
                </div>

                <div class="form-group">
                    <label for="login-password">密码</label>
                    <div class="input-with-icon">
                        <i class="fas fa-lock input-icon"></i>
                        <input type="password" id="login-password" placeholder="请输入密码">
                    </div>
                    <div class="error-message" id="login-password-error"></div>
                </div>

                <div class="forgot-password">
                    <a href="#" id="forgot-password">忘记密码？</a>
                </div>

                <div class="form-group">
                    <label for="login-captcha">验证码</label>
                    <div class="captcha-container">
                        <img id="login-captcha-image" src="/user/getcode" alt="验证码" style="height: 50px; cursor: pointer;" onclick="refreshLoginCaptcha()">
                        <div class="input-with-icon" style="flex: 2">
                            <i class="fas fa-shield-alt input-icon"></i>
                            <input type="text" id="login-captcha" placeholder="输入验证码">
                        </div>
                    </div>
                    <div class="error-message" id="login-captcha-error"></div>
                </div>

                <button class="btn" id="login-btn">登录</button>

                <!-- 添加切换链接 -->
                <div class="login-link">
                    没有账号？<a href="#" id="to-register">立即注册</a>
                </div>
            </div>
        </div>
    </div>
    <script>
        const api = axios.create({
            baseURL: 'http://localhost:3000/api',
            timeout: 10000,
            headers: {
                'Content-Type': 'application/json'
            }
        });

        // 状态管理
        const states = {
            STEP1: 'step1',
            STEP2: 'step2',
            STEP3: 'step3',
            LOGIN: 'login'
        };

        let currentState = states.STEP1;
        let registeredPhone = ''; // 存储注册成功的手机号

        // DOM元素
        const step1Content = document.getElementById('step1-content');
        const step2Content = document.getElementById('step2-content');
        const step3Content = document.getElementById('step3-content');
        const loginContent = document.getElementById('login-content');
        const stepIndicator = document.getElementById('step-indicator');
        const registerSuccessNotice = document.getElementById('register-success-notice');
        const loadingIndicator = document.createElement('div'); // 加载指示器

        // 初始化加载指示器
        loadingIndicator.className = 'loading-indicator';
        loadingIndicator.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            display: none;
        `;
        loadingIndicator.innerHTML = `
            <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
        `;
        document.body.appendChild(loadingIndicator);

        // 显示加载指示器
        function showLoading() {
            loadingIndicator.style.display = 'flex';
        }

        // 隐藏加载指示器
        function hideLoading() {
            loadingIndicator.style.display = 'none';
        }

        // 显示错误信息
        function showError(elementId, message) {
            const errorElement = document.getElementById(elementId);
            if (errorElement) {
                errorElement.textContent = message;
                errorElement.style.display = 'block';
            }
        }

        // 隐藏错误信息
        function hideError(elementId) {
            const errorElement = document.getElementById(elementId);
            if (errorElement) {
                errorElement.style.display = 'none';
            }
        }

        // 更新状态
        function updateState(newState) {
            currentState = newState;
            
            // 隐藏所有内容
            step1Content.classList.add('hidden');
            step2Content.classList.add('hidden');
            step3Content.classList.add('hidden');
            loginContent.classList.add('hidden');
            registerSuccessNotice.style.display = 'none';
            
            // 根据新状态显示相应内容
            if (newState === states.STEP1) {
                step1Content.classList.remove('hidden');
                stepIndicator.style.display = 'flex';
                refreshCaptcha();
            } else if (newState === states.STEP2) {
                step2Content.classList.remove('hidden');
                stepIndicator.style.display = 'flex';
            } else if (newState === states.STEP3) {
                step3Content.classList.remove('hidden');
                stepIndicator.style.display = 'flex';
            } else if (newState === states.LOGIN) {
                loginContent.classList.remove('hidden');
                stepIndicator.style.display = 'none';
                refreshLoginCaptcha();
                if (registeredPhone) {
                    document.getElementById('login-phone').value = registeredPhone;
                    registerSuccessNotice.style.display = 'block';
                }
            }
        }

        // 切换到登录页面
        document.getElementById('to-login-from-step1').addEventListener('click', function(e) {
            e.preventDefault();
            updateState(states.LOGIN);
        });

        document.getElementById('to-login-from-step2').addEventListener('click', function(e) {
            e.preventDefault();
            updateState(states.LOGIN);
        });

        document.getElementById('to-login').addEventListener('click', function(e) {
            e.preventDefault();
            updateState(states.LOGIN);
        });

        // 切换到注册页面
        document.getElementById('to-register').addEventListener('click', function(e) {
            e.preventDefault();
            updateState(states.STEP1);
        });

        // 密码强度检测
        document.getElementById('password').addEventListener('input', function(e) {
            const password = e.target.value;
            const strengthBar = document.getElementById('password-strength-bar');
            let strength = 0;
            
            if (password.length >= 6) strength += 25;
            if (password.match(/[a-z]/)) strength += 25;
            if (password.match(/[A-Z]/)) strength += 25;
            if (password.match(/[0-9]/)) strength += 25;
            
            strengthBar.style.width = strength + '%';
            
            if (strength <= 25) {
                strengthBar.style.background = '#e53935';
            } else if (strength <= 50) {
                strengthBar.style.background = '#ff9800';
            } else if (strength <= 75) {
                strengthBar.style.background = '#fdd835';
            } else {
                strengthBar.style.background = '#4caf50';
            }
        });

        // 初始化页面状态
        updateState(states.STEP1);

        // 表单验证工具函数
        function validatePhone(phone) {
            return /^1[3-9]\d{9}$/.test(phone);
        }

        function validateUsername(username) {
            return username.length >= 3 && username.length <= 20;
        }

        function validatePassword(password) {
            return password.length >= 6;
        }

        // 刷新验证码
        function refreshCaptcha() {
            const captchaImage = document.getElementById('captcha-image');
            captchaImage.src = '/user/getcode?' + new Date().getTime();
        }

        // 刷新登录验证码
        function refreshLoginCaptcha() {
            const captchaImage = document.getElementById('login-captcha-image');
            captchaImage.src = '/user/getcode?' + new Date().getTime();
        }

        // 验证手机号按钮点击事件
        document.getElementById('verify-btn').addEventListener('click', async function() {
            console.log('验证按钮被点击'); // 调试日志
            const phone = document.getElementById('phone').value;
            const captcha = document.getElementById('captcha').value;
            const agreement = document.getElementById('agreement').checked;
            
            // 重置错误信息
            document.getElementById('phone-error').style.display = 'none';
            document.getElementById('captcha-error').style.display = 'none';
            
            // 验证手机号
            if (!validatePhone(phone)) {
                document.getElementById('phone-error').textContent = '请输入有效的手机号码';
                document.getElementById('phone-error').style.display = 'block';
                return;
            }
            
            // 验证是否同意协议
            if (!agreement) {
                alert('请阅读并同意用户服务协议和隐私政策');
                return;
            }
            
            try {
                console.log('开始验证验证码'); // 调试日志
                // 验证验证码
                const response = await axios.get('/user/checkcode', {
                    params: {
                        code: captcha
                    }
                });
                
                console.log('验证码验证结果:', response.data); // 调试日志
                
                if (response.data.code === 'SUCCESS' && response.data.data === true) {
                    console.log('验证成功，准备跳转到下一步');
                    // 验证码正确，进入第二步
                    document.getElementById('step1').classList.remove('active');
                    document.getElementById('step1').classList.add('completed');
                    document.getElementById('step2').classList.add('active');
                    step1Content.classList.add('hidden');
                    step2Content.classList.remove('hidden');
                    // 保存手机号用于后续注册
                    localStorage.setItem('tempPhone', phone);
                } else {
                    console.log('验证失败:', response.data);
                    document.getElementById('captcha-error').textContent = '验证码错误';
                    document.getElementById('captcha-error').style.display = 'block';
                    refreshCaptcha();
                }
            } catch (error) {
                console.error('验证码验证失败:', error);
                document.getElementById('captcha-error').textContent = '验证码验证失败，请重试';
                document.getElementById('captcha-error').style.display = 'block';
                refreshCaptcha();
            }
        });

        // 头像上传预览
        const avatarPreview = document.getElementById('avatar-preview');
        const avatarImg = document.getElementById('avatar-img');
        const avatarInput = document.getElementById('avatar');

        // 图片压缩函数
        function compressImage(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function(e) {
                    const img = new Image();
                    img.src = e.target.result;
                    img.onload = function() {
                        const canvas = document.createElement('canvas');
                        // 设置压缩后的尺寸
                        let width = img.width;
                        let height = img.height;
                        const maxSize = 200; // 设置最大尺寸为200px
                        
                        if (width > height && width > maxSize) {
                            height = Math.round((height * maxSize) / width);
                            width = maxSize;
                        } else if (height > maxSize) {
                            width = Math.round((width * maxSize) / height);
                            height = maxSize;
                        }
                        
                        canvas.width = width;
                        canvas.height = height;
                        
                        const ctx = canvas.getContext('2d');
                        ctx.drawImage(img, 0, 0, width, height);
                        
                        // 转换为jpeg格式，设置较低的质量以减小文件大小
                        const compressedDataUrl = canvas.toDataURL('image/jpeg', 0.6);
                        resolve(compressedDataUrl);
                    };
                    img.onerror = function() {
                        reject(new Error('图片加载失败'));
                    };
                };
                reader.onerror = function() {
                    reject(new Error('文件读取失败'));
                };
            });
        }

        avatarPreview.addEventListener('click', function() {
            avatarInput.click();
        });

        avatarInput.addEventListener('change', async function(e) {
            if (e.target.files && e.target.files[0]) {
                try {
                    const file = e.target.files[0];
                    // 检查文件大小和类型
                    if (!file.type.startsWith('image/')) {
                        alert('请选择图片文件');
                        return;
                    }
                    
                    console.log('原始文件大小:', file.size / 1024, 'KB');
                    
                    // 压缩图片
                    const compressedDataUrl = await compressImage(file);
                    console.log('压缩后数据长度:', compressedDataUrl.length);
                    
                    // 显示压缩后的图片
                    avatarImg.src = compressedDataUrl;
                    avatarImg.style.display = 'block';
                    avatarPreview.querySelector('i').style.display = 'none';
                } catch (error) {
                    console.error('图片处理失败:', error);
                    alert('图片处理失败，请重试');
                }
            }
        });

        // 注册按钮点击事件
        document.getElementById('register-btn').addEventListener('click', async function() {
            console.log('注册按钮被点击'); // 调试日志
            
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm-password').value;
            const phone = localStorage.getItem('tempPhone'); // 获取之前保存的手机号
            const avatarImg = document.getElementById('avatar-img');
            
            // 重置错误信息
            document.getElementById('username-error').style.display = 'none';
            document.getElementById('password-error').style.display = 'none';
            document.getElementById('confirm-password-error').style.display = 'none';
            
            // 验证用户名
            if (!validateUsername(username)) {
                document.getElementById('username-error').textContent = '用户名长度应在3-20个字符之间';
                document.getElementById('username-error').style.display = 'block';
                return;
            }
            
            // 验证密码
            if (!validatePassword(password)) {
                document.getElementById('password-error').textContent = '密码长度至少为6个字符';
                document.getElementById('password-error').style.display = 'block';
                return;
            }
            
            // 验证确认密码
            if (password !== confirmPassword) {
                document.getElementById('confirm-password-error').textContent = '两次输入的密码不一致';
                document.getElementById('confirm-password-error').style.display = 'block';
                return;
            }
            
            try {
                console.log('开始注册请求'); // 调试日志
                const registerData = {
                    userName: username,
                    password: password,
                    telephone: phone,
                    avatarUrl: avatarImg.src !== '#' ? avatarImg.src : null
                };
                
                console.log('注册数据:', registerData); // 调试日志
                
                const response = await axios.post('/user/register', registerData);
                console.log('注册响应:', response); // 调试日志
                
                if (response.data) { // 直接判断response.data
                    console.log('注册成功，准备跳转到成功页面');
                    // 注册成功，进入第三步
                    document.getElementById('step2').classList.remove('active');
                    document.getElementById('step2').classList.add('completed');
                    document.getElementById('step3').classList.add('active');
                    step2Content.classList.add('hidden');
                    step3Content.classList.remove('hidden');
                    // 保存注册成功的手机号
                    localStorage.setItem('registeredPhone', phone);
                    // 清除临时手机号
                    localStorage.removeItem('tempPhone');
                } else {
                    console.log('注册失败:', response);
                    alert('注册失败，请重试');
                }
            } catch (error) {
                console.error('注册失败:', error);
                if (error.response && error.response.data && error.response.data.errMsg) {
                    alert('注册失败: ' + error.response.data.errMsg);
                } else {
                    alert('注册失败，请重试');
                }
            }
        });

        // 验证登录手机号
        function validateLoginPhone(phone) {
            // 中国大陆手机号验证规则
            const phoneRegex = /^1[3-9]\d{9}$/;
            return phoneRegex.test(phone);
        }

        // 验证登录密码
        function validateLoginPassword(password) {
            // 密码至少6位
            return password && password.length >= 6;
        }

        document.getElementById('login-btn').addEventListener('click', async function () {
            console.log('登录按钮被点击'); 
            const loginPhone = document.getElementById('login-phone').value;
            const loginPassword = document.getElementById('login-password').value;
            const loginCaptcha = document.getElementById('login-captcha').value.trim();

            // 重置错误信息
            document.getElementById('login-phone-error').style.display = 'none';
            document.getElementById('login-password-error').style.display = 'none';
            document.getElementById('login-captcha-error').style.display = 'none';

            // 验证手机号
            if (!validateLoginPhone(loginPhone)) {
                document.getElementById('login-phone-error').textContent = '请输入有效的手机号码';
                document.getElementById('login-phone-error').style.display = 'block';
                return;
            }
            // 验证密码
            if (!validateLoginPassword(loginPassword)) {
                document.getElementById('login-password-error').textContent = '密码长度至少为 6 个字符';
                document.getElementById('login-password-error').style.display = 'block';
                return;
            }

            try {
                console.log('开始验证验证码'); // 调试日志
                // 验证验证码
                let checkCodeResponse = await axios.get('/user/checkcode', {
                    params: {
                        code: loginCaptcha
                    }
                });
                
                console.log('验证码验证结果:', checkCodeResponse.data); // 调试日志
                if (checkCodeResponse.data.code !== 'SUCCESS' || !checkCodeResponse.data.data) {
                    document.getElementById('login-captcha-error').textContent = '验证码错误';
                    document.getElementById('login-captcha-error').style.display = 'block';
                    refreshLoginCaptcha(); // 验证码刷新
                    return;
                }

                // 验证码校验通过，发起登录请求
                console.log('开始登录请求'); 
                const loginData = {
                    telephone: loginPhone,
                    password: loginPassword,
                    code: loginCaptcha 
                };
                console.log('登录数据:', loginData); 

                const loginResponse = await axios.post('/user/login', loginData);
                console.log('登录响应:', loginResponse); 

                if (loginResponse.data && loginResponse.data.code === 'SUCCESS') { 
                    console.log('登录成功，准备跳转');
                    const { token, id } = loginResponse.data.data;
                    localStorage.setItem('token', token);
                    localStorage.setItem('userId', id);
                    localStorage.removeItem('tempPhone');
                    window.location.href = 'chat.html'; 
                } else {
                    console.log('登录失败:', loginResponse.data);
                    alert('登录失败，请检查账号信息');
                }
            } catch (error) {
                console.error('登录失败:', error);
                if (error.response && error.response.data && error.response.data.errMsg) {
                    alert('登录失败: ' + error.response.data.errMsg);
                } else {
                    alert('登录失败，请重试');
                }
            }
        });

        // 忘记密码链接
        document.getElementById('forgot-password').addEventListener('click', function(e) {
            e.preventDefault();
            alert('请联系管理员重置密码');
        });

        // 检查是否有注册成功的手机号
        const savedPhone = localStorage.getItem('registeredPhone');
        if (savedPhone) {
            registeredPhone = savedPhone;
            // 显示注册/登录页面
            updateState(states.LOGIN);
        } else {
            // 显示注册/登录页面
            updateState(states.STEP1);
        }

        // 初始化验证码
        refreshCaptcha();

        // 获取当前用户 ID
        function getCurrentUserId() {
            return localStorage.getItem('userId');
        }

        // 检查用户是否已登录
        function isAuthenticated() {
            return !!localStorage.getItem('token');
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('token');
            localStorage.removeItem('userId');
            switchState(states.LOGIN);
        }
    </script>
</body>

</html>